// flyer/chooseBgImg/index.js
const app = getApp();
const util = require('../../../utils/util.js');
const utils = require('../../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    flyerid: 0,
    flyerName: '',
    sendType: 0,
    gradeType: 0,
    flyerCount: '',
    currentImgId: 0,
    allImgs: [],
    currentImg: '',
    showImg: '',
    hasPre: false,
    hasNext: false,
    startY: 0,
    endY: 0
  },

  nextImg: function () {
    let allImages = this.data.allImgs;
    this.data.currentImgId += 1;
    this.data.currentImg = allImages[this.data.currentImgId].Path;
    let showImg = utils.formatAvater(allImages[this.data.currentImgId].Path, 'https://static.711688.net.cn/upload/share/');
    let hasNext = false;
    if (this.data.currentImgId < allImages.length - 1) {
      hasNext = true;
    }
    this.setData({
      showImg: showImg,
      hasPre: true,
      hasNext: hasNext
    })
  },

  preImg: function () {
    let allImages = this.data.allImgs;
    this.data.currentImgId -= 1;
    this.data.currentImg = allImages[this.data.currentImgId].Path;
    let showImg = utils.formatAvater(allImages[this.data.currentImgId].Path, 'https://static.711688.net.cn/upload/share/');
    let hasPre = false;
    if (this.data.currentImgId > 0) {
      hasPre = true;
    }
    this.setData({
      showImg: showImg,
      hasPre: hasPre,
      hasNext: true
    })
  },

  touchstart: function (e) {
    if (e.touches.length == 1) {
      this.data.startY = e.touches[0].clientY;
    }
  },

  touchend: function (e) {
    let that = this;
    if (e.changedTouches.length == 1) {
      let endY = e.changedTouches[0].clientY;
      var disY = that.data.startY - endY;
      if (disY >= 1 && that.data.hasNext) {//上滑
        that.nextImg();
      } else if (disY < -1 && that.data.hasPre) { //下拉
        that.preImg();
      }
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // if (options.flyerid > 0) {
    //   this.data.flyerid = options.flyerid
    // } else {
    //   this.data.flyerName = options.flyerName;
    //   this.data.sendType = options.sendType;
    //   this.data.flyerCount = options.flyerCount;
    // }
    this.data.flyerid = options.flyerid;
    this.data.flyerName = options.flyerName;
    this.data.sendType = options.sendType;
    this.data.flyerCount = options.flyerCount;
    this.data.gradeType = options.gradeType;
    this.getAllImg();
  },
  getAllImg: function () {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/leaflet/GetTemplateList?uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          let imgList = res.data.Data;
          let hasNext = false;
          let showImg = '';
          if (imgList.length > 0) {
            that.data.currentImg = imgList[0].Path;
            showImg = utils.formatAvater(imgList[0].Path, 'https://static.711688.net.cn/upload/share/')
            if (imgList.length > 1) {
              hasNext = true
            }
          }
          that.setData({
            hasNext: hasNext,
            showImg: showImg,
            allImgs: imgList
          })
        }
      }
    })
  },

  uploadBgImg: function () {
    let that = this;
    let pics = [];
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      complete: function (res) {
        var imgs = res.tempFilePaths;
        pics.push(imgs[0]);
        that.uploadimg({
          url: app.globalData.host + '/api/tool/upload?operation=share', //这里是你图片上传的接口
          path: pics, //这里是选取的图片的地址数组
        });
      }
    })
  },

  saveBgImg: function () {
    if (this.data.currentImg == '') {
      wx.showToast({
        title: '请选择或上传设计图',
        icon: 'none',
        mask: true
      })
      return;
    }
    wx.redirectTo({
      url: '../flyerSet/index?bgImg=' + this.data.currentImg + '&flyerid=' + this.data.flyerid + '&flyerName=' + this.data.flyerName + '&sendType=' + this.data.sendType + '&flyerCount=' + this.data.flyerCount+'&gradeType=' + this.data.gradeType,
    })
  },

  //多张图片上传（照片墙）
  uploadimg: function (data) {
    wx.showLoading({
      title: '提交中...',
      mask: true,
    })
    var that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    wx.uploadFile({
      url: data.url,
      filePath: data.path[i],
      name: 'fileData',
      formData: null,
      success: (resp) => {
        wx.hideLoading();
        success++;
        var str = resp.data
        var pic = JSON.parse(str);
        var pic_name = pic.Data;
        let allImgs = that.data.allImgs;
        let info = {};
        info.Path = pic_name;
        info.Title = '';
        allImgs.push(info);
        let showImg = utils.formatAvater(pic_name, 'https://static.711688.net.cn/upload/share/');
        that.setData({
          currentImg: pic_name,
          allImgs: allImgs,
          showImg: showImg
        })
      },
      fail: (res) => {
        fail++;
      },
      complete: (cp) => {
        i++;
        if (i == data.path.length) { //当图片传完时，停止调用     
          console.log('成功：' + success + " 失败：" + fail);
        } else { //若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimg(data);
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  }
})